package com.jieshuibao.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jieshuibao.common.config.Global;
import com.jieshuibao.common.req.BaseReq;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.VideoCard;
import com.jieshuibao.model.db.VideoCardExample;
import com.jieshuibao.model.db.VideoCardExample.Criteria;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.VideoCardRes;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.service.VideoCardService;

@Controller
@RequestMapping(value="/videoCard")
public class VideoCardController {
	@Resource
	private RedisService redisService;
	@Resource
	private UserService userService;
	@Resource
	private VideoCardService videoCardService;
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public Object videoCardList(HttpServletRequest request,@RequestBody BaseReq req){
		VideoCardRes res = new VideoCardRes();
		try {
			
			String cookie = request.getHeader("cookieId");
			if(cookie==null){
				res.setCode(BaseRes.RELOGIN_CODE);
				res.setDes(BaseRes.RELOGIN_DES);
				return res;
			}
			CookieUser cookieUser = redisService.getObejct(cookie,
					CookieUser.class);
			if(cookieUser==null){
				res.setCode(BaseRes.RELOGIN_CODE);
				res.setDes(BaseRes.RELOGIN_DES);
				return res;
			}
			String phoneNumber = cookieUser.getPhoneNumber();
			User user = userService.getUserByPhoneNumber(phoneNumber);
			if(user==null){
				res.setCode(BaseRes.RELOGIN_CODE);
				res.setDes(BaseRes.RELOGIN_DES);
				return res;
			}
			int sinceId = req.getSinceId();
			int maxId = req.getMaxId();
			VideoCardExample videoCardExample = new VideoCardExample();
			videoCardExample.setOrderByClause("video_card.price");
			videoCardExample.setPageIndex(sinceId-1);
			videoCardExample.setPageSize(maxId - sinceId + 1);
			Criteria createCriteria = videoCardExample.createCriteria();
			createCriteria.andDelFlagEqualTo(Global.SHOW);
			List<VideoCard> data = videoCardService.getPageVideoCard(videoCardExample);
			res.setData(data);
			res.setSinceId(sinceId);
			res.setMaxId(sinceId-1+data.size());
			res.setRows(data.size());
			res.setCode(BaseRes.SUCCESS_CODE);	
			res.setDes(BaseRes.SUCCESS_DES);
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes("网络抖动了");
			return res;
		}
	}

}
